<template>
    <div class="listDiv pd20">
        <div class="searchDiv">
            <el-form class="searchLeft" ref="serform" :model="obj.req" label-position="top">
                <el-form-item v-if="proxy.$useStore().getUser.flag.indexOf('2')!=-1" class="mr20 mb10">
                    <span class="btn add" @click="add">添加历史文件</span>
                    <Upfile buttontext="批量上传"  @upload="uploadfile" type="button" :accept="['application/vnd.ms-excel']" class="ml5" />
                    <span class="btn add ml5" @click="exporMud">下载模版</span>
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="创建时间：" prop="starttime">
                    <DateRange v-model:start="obj.req.starttime" v-model:end="obj.req.endtime"></DateRange>
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="文件名称：" prop="name">
                    <el-input v-model="obj.req.name" placeholder="请输入文件名称" class="search_key" clearable />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="文件编号：" prop="code">
                    <el-input v-model="obj.req.code" placeholder="请输入文件编号" class="search_key" clearable />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="承办单位/人：" prop="usernames">
                    <el-cascader v-model="obj.req.usernames" :props="getdeptP" placeholder="请选择承办单位/人" clearable :show-all-levels="false" />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="关键词：" prop="keyword">
                    <el-input v-model="obj.req.keyword" placeholder="请输入关键词" class="search_key" clearable />
                </el-form-item>
                <span class="btn search mb10 mr5" @click="obj.req.currentpage=1;init()">查询</span>
                <span class="btn refresh mb10 mr5" @click="proxy.$refs['serform'].resetFields();init()">重置</span>
                <span class="btn search mb10" @click="DownExcelExports" v-if="proxy.$useStore().getUser.flag.indexOf('4')!=-1">批量下载</span>
            </el-form>
        </div>
        <div class="table mb10" id="tb">
            <ul class="head">
                <li class="li30"><el-checkbox v-model="obj.checkAll" :indeterminate="obj.isIndeterminate" @change="handleCheckAllChange"></el-checkbox></li>
                <li class="li100 liflex fixed ls">文件名称</li>
                <li class="li150">文件编号</li>
                <li class="liflex">承办单位</li>
                <li class="liflex">关键词</li>
                <li class="li260">简介</li>
                <li class="litime"><HeadSort text="录入时间" v-model:sort="obj.req.sort" :index="1" @sortClick="obj.req.currentpage=1;init()" /></li>
                <li class="liaction li220">操作</li>
            </ul>
            <div class="body">
                <ul v-for="(x,i) in obj.ary" :key="x">
                    <li class="li30"><el-checkbox v-model="obj.checks[i]" size="large" @change="handleCheck" /></li>
                    <li class="li100 liflex fixed ls"><span class="lineOne">{{x.name}}</span></li>
                    <li class="li150 flex-center"><span class="lineOne">{{x.code}}</span></li>
                    <li class="liflex flex-center">{{x.dept_name}}</li>
                    <li class="liflex flex-center">{{ x.keyword }}</li>
                    <li class="li260">
                        <el-tooltip
                                    class="box-item"
                                    effect="dark" :disabled="x.synopsis.length<19"
                                    :content="x.synopsis"
                                    placement="top-start"
                                >
                                <template #content><div style="width: 600px;">{{ x.synopsis }}</div></template>
                            <span class="lineOne">{{x.synopsis}}</span>
                        </el-tooltip></li>
                    <li class="litime flex-center">{{ x.intime }}</li>
                    <li class="liaction li220 flex-center">
                        <u @click.prevent="edit(x)">编辑</u>
                        <u @click.prevent="read(x)">详情</u>
                        <u @click.prevent="showShare(x)" v-if="proxy.$useStore().getUser.flag.indexOf('5')!=-1">分享</u>
                        <u @click.prevent="setjing(x,x.boutique==0?'加精':'取消加精')" 
                            v-if="proxy.$useStore().getUser.flag.indexOf('2')!=-1"
                            >
                            <el-icon :class="[x.boutique==1?'staricon':'StarFilled']">
                                <Star v-if="x.boutique==0" />
                                <StarFilled v-if="x.boutique==1" />
                            </el-icon>
                        </u>
                        <u @click.prevent="obj.showLog_id=x.file_id;obj.showLog_name=x.name;">日志</u>
                        <u @click.prevent="DownExcelExport('历史文件',[x.file_id])" v-if="proxy.$useStore().getUser.flag.indexOf('4')!=-1">下载</u>
                        <DelConfirm @yesClick="del(x)" v-if="proxy.$useStore().getUser.flag.indexOf('3')!=-1" />
                    </li>
                </ul>
            </div>
        </div>
        <ElConfigProvider :locale="locale">
            <el-pagination layout="total, prev, pager, next, jumper" background :total="obj.req.count" :page-size="obj.req.pagesize" v-model:currentPage="obj.req.currentpage" @current-change="init()" />
        </ElConfigProvider>
        <el-dialog v-model="obj.shareF.file_id" :title="`分享 ${obj.shareF.name}`" :close-on-click-modal="false" destroy-on-close>
            <AhareF :shareF="obj.shareF" @close="obj.shareF.file_id = false" />
        </el-dialog>
        <div v-if="obj.showLog_id" class="showLogbox">
            <ReadFileLog :id="obj.showLog_id" :name="obj.showLog_name" :tags="['文件管理','历史文件','承办进展']" @close="obj.showLog_id=false" />
        </div>
    </div>
</template>

<script setup>
    import { reactive,getCurrentInstance,onMounted,onActivated } from 'vue'
    import { Star,StarFilled } from "@element-plus/icons-vue";
    import Pager from '@/components/pager.vue'
    import DelConfirm from '@/components/del_confirm.vue'
    import DateRange from '@/components/date_range.vue'
    import HeadSort from '@/components/head_sort.vue'
    import AhareF from '../shareF.vue'
    import ReadFileLog from '../readFileLog.vue'
    import Upfile from '@/components/upfile_single.vue'

    import locale from "element-plus/es/locale/lang/zh-cn";
    import dayjs from 'dayjs'
    let { proxy } = getCurrentInstance()

    let obj = reactive({
        showLog_id: false,
        showLog_name: '',
        ary:[],
        req:{
            "type": "history",
            "starttime": "",
            "endtime": "",
            "name": "",
            "code": "",
            "company_name": "",
            usernames: [],
            "user_name": "",
            "keyword": "",
            "sort": "",
            "currentpage": 1,
            "pagesize": 10,
            count: 0,
        },
        companys: [],
        shareF: {
            "file_id": false,
        },
        file_ids: [],
        checks: [],
        checkAll: false,
        isIndeterminate: false
    })

    onActivated(async()=>{
        obj.companys = await proxy.$setting.getdepts()
        init()
    })

    const init=()=>{
        obj.req.company_name = obj.req.usernames&&obj.req.usernames.length==1?obj.req.usernames[0]:''
        obj.req.user_name = obj.req.usernames&&obj.req.usernames.length>1?obj.req.usernames[1]:''
        proxy.$ajax({
            url: '/user/file/list',
            data: obj.req,
            bfLoading: true
        }).then(d => {
            if(d.success){
                obj.ary = d.msg.list
                obj.req.count = d.msg.count
                obj.checks = new Array(obj.ary.length).fill(false)
            }
        }).catch(() => { })
    }

    const exporMud=()=>{
        const link = document.createElement('a');
        link.href = `${window.location.origin}/temp/历史文件导入模板.xls`;
        link.download = '历史文件导入模板.xls';
        link.target = "_blank";
        link.click();
    }

    const getdeptP = {
        lazy: true,
        checkStrictly: true,
        label:'name', value: 'name',
        async lazyLoad(node, resolve) {
            const { level,value,data } = node
            setTimeout(async() => {
                if(level==0){
                    const arr = await proxy.$setting.getdepts()
                    resolve(arr)
                }else if(level==1){
                    let arr = await proxy.$setting.getusers(data.id||'')
                    arr.map(e=>{
                        e.leaf = true
                    })
                    resolve(arr)
                }else{resolve([])}
            }, 200);
        }
    }

    let add = () => {
        proxy.routerPushMixin("/hisfileEdit",{id:0})
    }
    let edit = x => {
        proxy.routerPushMixin("/hisfileEdit",{id:x.file_id,dept_name:x.dept_name,user_name:x.user_name,codetime:x.codetime})
    }

    let read = x => {
        proxy.routerPushMixin("/hisfileEdit",{id:x.file_id,dept_name:x.dept_name,user_name:x.user_name,codetime:x.codetime,disabled:true})
    }

    const showShare = x => {
        obj.shareF.file_id = x.file_id
        obj.shareF.name = x.name
    }

    const setjing = (x,text) => {
        proxy.$ajax({
            url: '/user/file/boutique/history',
            data: { file_id: x.file_id },
            bfLoading: true
        }).then(d => {
            if(d.success){
                proxy.elMessageMixin(`${text}成功`, 'success')
                init()
            }else{
                proxy.elMessageMixin(d.err, 'error')
            }
        }).catch(() => { })
    }

    let del = x => {
        proxy.$ajax({
            url: '/user/file/delete',
            data: { file_id: x.file_id },
            bfLoading: true
        }).then(d => {
            if(d.success){
                proxy.elMessageMixin("删除成功", 'success')
                init()
            }else{
                proxy.elMessageMixin(d.err, 'error')
            }
        }).catch(() => { })
    }

    //批量导入
    const uploadfile = (e)=>{
        let upresult = ''
        obj.updata = []
        const xlsImport = async () =>{
            const list = await proxy.$util.xlsImport(proxy,e)
            // console.log('list',list)
            // return
            let keys = {'是否精品文件':'boutique','文件编号':'code','文件名称':'name','文件简介':'synopsis','关键词':'keyword','首长批示':'instructions','督办情况':'supervise'}
            let updata = []
            list.map((item,idx)=>{
                let obj = {
                    "file_id": "0",
                    "boutique": 0,
                    "code": "",
                    "name": "",
                    "state": "",
                    "synopsis": "",
                    "keyword": "",
                    "company_id": 0,
                    "supervise": "",
                    "imgs": "",
                    "files": "",
                    "instructions": [{msg:'',intime:dayjs().format('YYYY-MM-DD HH:mm:ss')}]
                }
                if(idx>0){
                    Object.keys(item).forEach((key) => {
                        let val = item[key].replace(/\s+/g, '')
                        if(val){
                            if(key==='首长批示'){
                                const ins = [{msg:val.toString(),intime: dayjs().format('YYYY-MM-DD HH:mm:ss')}]
                                obj[keys[key]] = JSON.stringify(ins)
                            }else if(key==='是否精品文件'){
                                obj[keys[key]] = val=='非精品文件'?1:0
                            }else{
                                obj[keys[key]] = val.toString();
                            }
                        }
                    });
                    if(!item['是否精品文件']||!item['文件编号']||!item['文件名称']||!item['文件简介']||!item['关键词']||!item['首长批示']){
                        upresult = '文件内容不完整，请填写完所有选项再导入！'
                    }
                    updata.push(obj)
                }
            })
            if(upresult){
                proxy.elMessageMixin(upresult, 'error', 5)
                return
            }
            // console.log('updata',updata);
            // return
            if(updata.length){
                upresult = ''
                for (let i = 0; i < updata.length; i++) {
                    const e = updata[i];
                    const err = await exup(i,e)
                    upresult += err
                }
                if(upresult){
                    upresult = `${upresult}`
                    proxy.elMessageMixin(`有数据导入失败，${upresult}`, 'error', 8)
                }else{
                    proxy.elMessageMixin('导入成功', 'success', 2)
                }
                obj.req.currentpage = 1
                init()
            }
        }
        xlsImport()
    }

    const exup=(i,data)=>{
        return new Promise((resovle,reject)=>{
            proxy.$ajax({
                url: 'user/file/history/design',
                data: data,
                bfLoading: true,
                isAlertErrorMsg: false
            }).then(data => {
                if(data.success){
                    resovle('')
                }else{resovle(`【表格第${i+2}行：${data.err||'未知原因'}】`)}
            }).catch(() => {resovle('未知原因')}) 
        })
    }

    const handleCheckAllChange = (val) => {
        obj.checks = new Array(obj.ary.length).fill(val)
        obj.isIndeterminate = false
    }

    const handleCheck=(val)=>{
        obj.isIndeterminate = obj.checks.some(x=>x) && !obj.checks.every(x=>x)
        obj.checkAll = obj.checks.every(x=>x)
    }

    const DownExcelExports=()=>{
        let file_ids = []
        for (let i = 0; i < obj.ary.length; i++) {
            if (obj.checks[i]){
                file_ids.push(obj.ary[i].file_id)
            }
        }
        DownExcelExport('历史文件',file_ids)
    }

    let get = (file_id) => {
        return new Promise((resolve, reject) => {
            proxy.$ajax({
                url: '/user/file/get',
                data: { file_id: file_id },
                bfLoading: true
            }).then(d => {
                resolve(d.msg||{})
            }).catch(e => {
                reject({})
            })
        })
    }

    const DownExcelExport=async(typename,ids)=>{
        if(ids.length==0){
            proxy.elMessageMixin("请选择文件", 'error')
            return
        }
        let list = []
        for (let i = 0; i < ids.length; i++) {
            const o = await get(ids[i])
            const listo = obj.ary.find(e => e.file_id == ids[i])
            const item = {
                ...o,
                boutique: o.boutique == 1 ? '是' : '否',
                state: proxy.$setting.globalData.fileStates[o.state||0].name,
                dept_name: listo?listo.dept_name:'',
                user_name: listo?listo.user_name:'',
                imgs: o.imgs?o.imgs.split(',').map(e=>`${proxy.$setting.globalUrl.fileurl}/files/${e}`):'',
                files: o.imgs?o.files.split(',').map(e=>`${proxy.$setting.globalUrl.fileurl}/files/${e}`):'',
                instructions: o.instructions?o.instructions.map((e,i)=>`${e.intime}：${e.msg}${i==o.instructions.length-1?'。':'；'}`):''
            }
            list.push(item)  
        }
        // return
        const fields = [
            'file_id',
            'code',
            'codetime',
            'boutique',//精品文件
            'name',
            // 'category',//类别 0历史文件/1普通文件/3舆情事件
            'state',//办理进度
            'synopsis',
            'keyword',
            'dept_name',//承办单位
            'user_name',//承办人
            'intime',
            'imgs',//图片
            'files',//文件
            'instructions',//首长批示
            'supervise',
            // 'province',
        ]
        const headers = [
            '文件ID',
            '文件编号',
            '编号生成时间',
            '精品文件',//
            '文件名称',
            // '类别',//
            '办理进度',//
            '文件简介',
            '关键词',
            '承办单位',//
            '承办人',//
            '上传时间',
            '图片',//
            '文件',//
            '首长批示',//
            '督办情况',
            // '省份信息',
        ]
        proxy.$util.ExcelExport(list, fields, headers, `${typename}-${dayjs().format('YYYYMMDDHHmmss')}`, 'Sheet', null, [], true)
    }
</script>

<style scoped>
</style>